﻿using System;
using System.Collections.Generic;
using System.IO;
using Substitute.Base;

namespace Substitute.Readers
{
    [ReaderHandles("ini")]
    class INIReader : Base.VariableReader
    {
        public override bool LoadVariables(string fileName, Base.Logger logger)
        {
            using (var reader = File.OpenText(fileName))
            {
                logger.WriteLog(@"INI Read : File Open");

                string currentLine;
                string currentSection = "";
                while (!reader.EndOfStream)
                {
                    currentLine = reader.ReadLine().Trim();
                    if (currentLine != string.Empty)
                    {
                        if ((currentLine.StartsWith("[")) && (currentLine.EndsWith("]")))
                        {
                            currentSection = currentLine.Substring(1, currentLine.Length - 2);
                            logger.WriteLog(@"INI Read : Section Found - " + currentSection);

                            if (!this.Sections.ContainsKey(currentSection))
                                this.Sections.Add(currentSection, new Dictionary<string, string>());
                        }
                        else
                        {
                            if (currentLine.Contains("="))
                            {
                                int splitIndex = currentLine.IndexOf('=');
                                if (this.Sections.ContainsKey(currentSection))
                                {
                                    this.Sections[currentSection].Add(currentLine.Substring(0, splitIndex).ToUpper(), currentLine.Substring(splitIndex + 1));
                                    logger.WriteLog(String.Format(@"INI Read : Key Found - Key:{0} Value:{1}", currentLine.Substring(0, splitIndex).ToUpper(), currentLine.Substring(splitIndex + 1)));
                                }
                            }
                        }
                    }
                }
                reader.Close();

                logger.WriteLog(@"INI Read : Complete");
                return true;
            }
        }
    }
}
